import React, { useImperativeHandle, forwardRef, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native'
import { Provider as AntDesignProvider, Button, Modal, Toast, WhiteSpace, WingBlank, ActivityIndicator } from '@ant-design/react-native'
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import { connect } from 'react-redux'
import { signMessage } from 'react-native-web3-wallet';
import { ethers } from "ethers";
import { pTx } from "../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../realm"
import AsyncStorage from '@react-native-async-storage/async-storage';

const PersonalSign = React.forwardRef((props, ref) => {
    const wallet = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered('current = true');
    })[0];
    const [open, setOpen] = useState(false)
    const [pageLoading, setPageLoading] = useState(true)
    const [loading, setLoading] = useState(false)
    const [payload, setPayload] = useState(null)
    const [params, setParams] = useState(null)
    const [method, setMethod] = useState(null)

    useImperativeHandle(ref, () => ({
        // methods connected to `ref`
        setOpen,
        show
    }))
    // internal method
    const show = async (data) => {
        try {
            setOpen(true)
            setPayload(payload)
            const { type, payload = {} } = JSON.parse(data) || {};
            const { method, params } = payload;
            setPayload(payload)
            setMethod(method)
            setParams(params)
            setPageLoading(false)
        } catch (error) {

        }
    }
    const close = () => {
        setOpen(false)
        props.updateParentMessage({ id: method, error: "error", time: payload.time });
    }

    const clickSendTransaction = async () => {
        Modal.prompt(
            '请输入密码',
            '',
            [
                {
                    text: '取消',
                    style: 'cancel',
                },
                {
                    text: '确认',
                    onPress: (res) => {
                        return new Promise(async (resolve, reject) => {
                            resolve()
                            try {
                                setLoading(true)
                                const signedMs = await signMessage(
                                    wallet.keystore,
                                    res,
                                    ethers.utils.toUtf8String(params[0])
                                )
                                props.updateParentMessage({ id: method, result: signedMs, time: payload.time });
                            } catch (error) {
                                console.log(error)
                                Toast.info('密码错误')
                                props.updateParentMessage({ id: method, error: error, time: payload.time });
                            }
                            setLoading(false)
                            setOpen(false)
                        })

                    },
                },
            ],
            '',
            '',
        )

    }
    return (
        <Modal
            popup
            visible={open}
            style={styles.Modal}
            animationType="slide-up">
            <View style={styles.ModalBox}>
                <IconOutline name="close" style={styles.close} onPress={close} />
                {pageLoading ?
                    (<View >
                        <Text style={styles.title}>获取签名</Text>
                        <View style={styles.activityIndicator} >
                            <ActivityIndicator size="xl" />
                        </View>
                    </View>) : (
                        <View>
                            <Text style={styles.title}>确认签名</Text>
                            <View style={styles.page} >
                                <View style={styles.row} >
                                    <Text style={styles.label}>钱包地址</Text>
                                    <Text style={styles.value}>{wallet.address}</Text>
                                </View>
                                <View style={styles.row} >
                                    <Text style={styles.label}>签名内容</Text>
                                    <Text style={styles.value}>
                                        {ethers.utils.toUtf8String(params[0])}
                                    </Text>
                                </View>
                                <Button type="primary" loading={loading} disabled={loading} onPress={clickSendTransaction}>
                                    确定
                                </Button>
                            </View>
                        </View>
                    )
                }
            </View>
        </Modal>
    );
})

const mapState = state => {
    return {
    }
}

export default connect(mapState, {}, null, { forwardRef: true })(PersonalSign)

const styles = StyleSheet.create({
    Modal: {
        borderTopRightRadius: pTx(15),
        borderTopLeftRadius: pTx(15),
    },
    ModalBox: {
        position: "relative",
    },
    title: {
        textAlign: "center",
        paddingVertical: pTx(15),
        borderWidth: pTx(1),
        borderColor: "rgba(0,0,0,0.08)",
    },
    close: {
        position: "absolute",
        right: pTx(15),
        top: pTx(20),
        fontSize: pTx(16),
        zIndex: 9
    },
    activityIndicator: {
        minHeight: pTx(150),
        justifyContent: "center"
    },
    page: {
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(25),
    },
    row: {
        flexDirection: "row",
        marginBottom: pTx(15),
        paddingBottom: pTx(15),
        borderBottomWidth: pTx(1),
        borderColor: "rgba(0,0,0,0.08)",
    },
    label: {
        minWidth: pTx(100),
        fontSize: pTx(11),
        color: "#999"
    },
    value: {
        maxWidth: pTx(240),
        fontSize: pTx(11),
        color: "#333",
        flexWrap: "wrap",
    }
})